package com.mirror.tk.core.biz.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.mirror.tk.core.biz.common.Result;
import com.mirror.tk.core.biz.dto.ResTaobaoCoupon;
import com.mirror.tk.core.biz.dto.ResTaobaoGoods;
import com.mirror.tk.core.biz.dto.ResTaobaoShop;
import com.mirror.tk.core.constant.ErrorCode;
import com.mirror.tk.core.utils.TaobaoUrlUtil;
import com.mirror.tk.core.utils.TransferUtil;
import com.mirror.tk.core.utils.UrlUtil;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.NTbkShop;
import com.taobao.api.request.TbkCouponGetRequest;
import com.taobao.api.request.TbkItemInfoGetRequest;
import com.taobao.api.request.TbkShopRecommendGetRequest;
import com.taobao.api.response.TbkCouponGetResponse;
import com.taobao.api.response.TbkCouponGetResponse.MapData;
import com.taobao.api.response.TbkItemInfoGetResponse;
import com.taobao.api.response.TbkShopRecommendGetResponse;

/**
 * 调用淘宝接口
 * @author Administrator
 *
 */
@Service
public class TaobaoBiz {
	
	private static Logger log = LoggerFactory.getLogger(TaobaoBiz.class);
	
	@Value("${taobao.app.key}")
	private String appkey;

	@Value("${taobao.app.secret}")
	private String secret;

	@Value("${taobao.app.url}")
	private String url;

	private TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
	
	/**
	 * 根据商品ID抓取商品信息
	 * @param numIid
	 * @return
	 */
	public Result<ResTaobaoGoods> fetchGoods(Long numIid) {
		if(numIid == null ) {
			return new Result<ResTaobaoGoods>().fail(ErrorCode.PARAM_NULL, ErrorCode.PARAM_NULL_DES);
		}
		String id = String.valueOf(numIid);
		
		TbkItemInfoGetRequest req = new TbkItemInfoGetRequest();
		req.setPlatform(1L);
		req.setNumIids(id);
		TbkItemInfoGetResponse rsp = null;
		try {
			rsp = client.execute(req);
		} catch (ApiException e) {
			log.error("",e);
			return new Result<ResTaobaoGoods>().fail(ErrorCode.TAOBAO_API_ERROR, ErrorCode.TAOBAO_API_ERROR_DES+":"+e.getErrMsg());
		}
		ResTaobaoGoods result = new ResTaobaoGoods();
		if(rsp != null && rsp.getErrorCode() == null) {
			List<com.taobao.api.response.TbkItemInfoGetResponse.NTbkItem> tbRsp = rsp.getResults();
			if(CollectionUtils.isEmpty(tbRsp)) {
				return new Result<ResTaobaoGoods>().success(result);
			}
			com.taobao.api.response.TbkItemInfoGetResponse.NTbkItem item = tbRsp.get(0);
			result.setImgUrl(item.getPictUrl());
			result.setNumIid(item.getNumIid());
			result.setPrice(TransferUtil.strToDouble(item.getReservePrice()));
			result.setFinalPrice(TransferUtil.strToDouble(item.getZkFinalPrice()));
			result.setSmallImg(item.getSmallImages());
			result.setTitle(item.getTitle());
			result.setUrl(item.getItemUrl());
			result.setFinalPrice(TransferUtil.strToDouble(item.getZkFinalPrice()));
			result.setUserType(item.getUserType());
			result.setVolume(item.getVolume());
			result.setSellerId(item.getSellerId());
			return new Result<ResTaobaoGoods>().success(result);
		}
		return new Result<ResTaobaoGoods>().success(result);
	}

	/**
	 * 根据URL抓取商品信息
	 * @param url
	 * @return
	 */
	public Result<ResTaobaoGoods> fetchGoods(String goodsUrl) {
		if(url == null || !StringUtils.isNotBlank(goodsUrl)) {
			return new Result<ResTaobaoGoods>().fail(ErrorCode.PARAM_NULL, ErrorCode.PARAM_NULL_DES);
		}
		String id = TaobaoUrlUtil.fetchItemId(goodsUrl);
		return fetchGoods(Long.valueOf(id));
	}
	
	/**
	 * 根据商品ID查询店铺
	 * @param numIid
	 * @return
	 */
	public Result<ResTaobaoShop> fetchShop(Long numIid) {
		Result<ResTaobaoGoods> goodsResult = fetchGoods(numIid);
		if(!goodsResult.isSuccess()) {
			return new Result<ResTaobaoShop>().fail(goodsResult.getCode(),goodsResult.getDescription());
		}
		ResTaobaoGoods goods = goodsResult.getData();
		if(goods == null || goods.getNumIid() == null) {
			return new Result<ResTaobaoShop>().success(new ResTaobaoShop());
		}
		
		Long sellerId = goods.getSellerId();
		TbkShopRecommendGetRequest req = new TbkShopRecommendGetRequest();
		req.setFields("user_id,shop_title,shop_type,seller_nick,pict_url,shop_url");
		req.setUserId(sellerId);
		req.setCount(20L);
		req.setPlatform(1L);
		TbkShopRecommendGetResponse rsp = null;
		try {
			rsp = client.execute(req);
		} catch (ApiException e) {
			log.error("",e);
			return new Result<ResTaobaoShop>().fail(ErrorCode.TAOBAO_API_ERROR, ErrorCode.TAOBAO_API_ERROR_DES+":"+e.getErrMsg());
		}
		
		ResTaobaoShop result = new ResTaobaoShop();
		if(!CollectionUtils.isEmpty(rsp.getResults())) {
			NTbkShop shop = rsp.getResults().get(0);
			result.setPictUrl(shop.getPictUrl());
			result.setSellerId(shop.getUserId());
			result.setSellerNick(shop.getSellerNick());
			result.setShopTitle(shop.getShopTitle());
			result.setShopType(shop.getShopType());
			result.setShopUrl(shop.getShopUrl());
		}
		return new Result<ResTaobaoShop>().success(result);
	}

	/**
	 * 根据商品ID和优惠劵ID获取优惠劵信息
	 * @param numIid
	 * @return
	 */
	public Result<ResTaobaoCoupon> fetchCoupon(Long itemId, String activityId) {
		if (null == itemId || !StringUtils.isBlank(activityId)) {
			return new Result<ResTaobaoCoupon>().fail(ErrorCode.PARAM_NULL, ErrorCode.PARAM_NULL_DES);
		}
		TbkCouponGetRequest req = new TbkCouponGetRequest();
		req.setItemId(itemId);
		req.setActivityId(activityId);
		TbkCouponGetResponse rsp = null;
		try {
			rsp = client.execute(req);
		} catch (ApiException e) {
			log.error("", e);
			return new Result<ResTaobaoCoupon>().fail(ErrorCode.TAOBAO_API_ERROR, ErrorCode.TAOBAO_API_ERROR_DES + ":" + e.getErrMsg());
		}
		ResTaobaoCoupon res = new ResTaobaoCoupon();
		if (null != rsp.getData()) {
			MapData da = rsp.getData();
			BeanUtils.copyProperties(da, res);
		}
		return new Result<ResTaobaoCoupon>().success(res);
	}
	
	public static void main (String a[]){
		Map<String, String> map = UrlUtil.URLRequest("https://detail.tmall.com/item.htm?spm=a1z10.1-b.w11104943-15151416542.11.f9BvVx&id=534354715015");
		System.out.println(map.get("id"));
	}
}
